import re
from staffInfo.department.config import *
from common.read_file import read_json
from common.utils import compare_str, empty
from albertv0 import *


def dep_search(query_str):
    # 中文字符
    pattern = re.compile("[\u4e00-\u9fa5]{1,}$", re.I)
    match = pattern.match(query_str)
    if match is not None:
        return search_by_keys(query_str, 'dep_name')
    # 可能是ID 或者是 拼音
    pattern = re.compile('^[a-zA-Z0-9]+$', re.I)
    match = pattern.match(query_str)
    if match is not None:
        return search_by_keys(query_str, 'dep_id', 'spell', 'abbreviation')
    return []
    pass


def search_by_keys(query_str, *search_key):
    dep_tree, dep_dict = get_data()
    # 记录搜索得到的结果
    search_list_result = []
    results = []
    for dep in dep_dict.values():
        for key in search_key:
            if compare_str(dep[key], query_str):
                search_list_result.append(dep['dep_id'])
                results.append(init_item(dep))
                break
    children_rs = get_children(search_list_result, dep_tree, dep_dict)
    # 搜索所有的子部门
    return results + children_rs
    pass


def get_children(dep_id_list, dep_tree, dep_dict):
    results = []
    if empty(dep_id_list):
        return results
    for dep_id in dep_id_list:
        results.extend(get_children_by_one(dep_id, dep_tree, dep_dict))
    return results
    pass


def get_children_by_one(dep_id, dep_tree, dep_dict):
    results = []
    if dep_id not in dep_tree:
        return results
    dep_list = dep_tree[dep_id]
    index = 0
    while True:
        if index + 1 > len(dep_list):
            break
        results.append(init_item(dep_dict[dep_list[index]]))
        if dep_list[index] in dep_tree:
            dep_list.extend(dep_tree[dep_list[index]])
        index += 1
        pass
    return results
    pass


def init_item(item):
    return {
        'text': item['dep_name'],
        'subtext': item['dep_id'],
        'actions': [
            ClipAction(text="ClipAction", clipboardText=item['dep_id']),
        ]
    }
    pass


def get_data():
    rs = read_json(DEPARTMENT_SAVE_PATH)
    return rs['dep_tree'], rs['dep_dict']
    pass
